/*
 * TimerTask.cpp
 *
 *  Created on: 15 Sep, 2017
 *      Author: buffon
 */
#include "TimerTask.h"
#include "exports_c.h"
#include <unistd.h>
#include "json/json.h"
using namespace Json;
//TimerTask::TimerTask(){
//
//}

TimerTask::TimerTask(char* buffer,int begin,int end,int nTvId,std::string postUrl)
{
	pBuffer = buffer;
	tvsId = nTvId;
	url.assign(postUrl);
	nBegin = begin;
	nEnd = end;
}

TimerTask::~TimerTask(){

}

bool TimerTask::saveToFile(char* pData,int length){
	cout << "saveToFile"<<endl;
	bool bOk = false;

	FILE *file = fopen("tmp.m4a","wb");
	if(file){
		fwrite(pData,length,1,file);
		fclose(file);
	}
	bOk = true;

	cout << "saveToFile End"<<endl;
	return bOk;
}

void TimerTask::run(){

	//指纹 log
	time_t ts = time(NULL);
	tm* pT = localtime(&ts);
	char codefile[100] = {0};
	sprintf(codefile,"code_%04d_%03d_%02d.txt",pT->tm_year,pT->tm_yday,pT->tm_hour);

	//日志
	FILE* fp = NULL;
	fp = fopen(codefile,"a+");

		clock_t begin = clock();

		char *pSrc =  NULL;
		pSrc = pBuffer + nBegin;
//...?
		saveToFile(pSrc,nEnd - nBegin);

		codegen_response_t *response = codegen_file("tmp.m4a", 0,0,0);
		char *p = make_json_string(response);

		time_t currtime = time(NULL);
		tm* pTm = localtime(&currtime);
		char filename[100] = {0};
		sprintf(filename,"\n%02d-%02d-%02d\n",pTm->tm_hour,pTm->tm_min,pTm->tm_sec);

		if(fp){
			fwrite(filename,1,strlen(filename),fp);
			fwrite(p,1,strlen(p),fp);
		}
	try{
		Json::Value rData;
		rData["tvId"] = tvsId;
		rData["echoprintString"] = Json::Value(p);

		string strData = "tvId=";
		strData.append(Json::Value(tvsId).asString());
		strData.append("&echoprintString=");
		strData.append(p);
		string strResp;
		CURLcode nRet = http.Post(url, strData,strResp);
		if(nRet != CURLE_OK)
		{
			printf("access url:%s error\n", url.c_str());
		}
		Json::Reader reader;
		Json::Value value;
		if(!reader.parse(strResp, value))
		{
			printf("parse response error:%s\n", strResp.c_str());
//			return;
		}
	    try {
	        string strRet = value["infocode"].asString();
	        string strMsg;
	        if(strRet.compare("0")== 0 )
	        {
	            strMsg = value["info"].asString();
	            printf("Msg:%s\n", strMsg.c_str());
	        }
	        if(fp){
				fwrite("\r",1,strlen("\r"),fp);
				fwrite(strMsg.c_str(),1,strlen(strMsg.c_str()),fp);
	       }

	    } catch (std::runtime_error msg) {
	        printf("get json error:%s\n", strResp.c_str());
	        cout << msg.what()<<endl;
	        if(fp){
				fwrite("\r",1,strlen("\r"),fp);
				fwrite(msg.what(),1,strlen(msg.what()),fp);
		   }
	    }

	}
	catch(exception& e){
		cout << e.what()<<endl;
	}

	free_json_string(response,p);

	if(fp){fclose(fp);}

}
